package com.enfi.api.util;

import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wind
 * @date 2020/4/8
 */
public class DateTimeUtils {
    private static final List<String> formatList = new ArrayList<>(4);
    static{
        formatList.add("yyyy-MM");
        formatList.add("yyyy-MM-dd");
        formatList.add("yyyy-MM-dd HH:mm");
        formatList.add("yyyy-MM-dd HH:mm:ss");
    }
    public static boolean isDateTime(String source) {
        if (StringUtils.isEmpty(source)) {
            return false;
        }
        source = source.trim();
        if(source.matches("^\\d{4}-\\d{1,2}$")){
            return true;
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")){
            return true;
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
            return true;
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
            return true;
        }else {
            return false;
        }
    }
    public static Date convert(String source) {
        if (StringUtils.isEmpty(source)) {
            return null;
        }
        source = source.trim();
        if(source.matches("^\\d{4}-\\d{1,2}$")){
            return parseDate(source, formatList.get(0));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")){
            return parseDate(source, formatList.get(1));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
            return parseDate(source, formatList.get(2));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
            return parseDate(source, formatList.get(3));
        }else {
            return null;
        }
    }
    public static   Date parseDate(String dateStr, String format) {
        try {
            DateFormat dateFormat = new SimpleDateFormat(format);
            return dateFormat.parse(dateStr);
        } catch (Exception e) {

        }
        return null;
    }
}
